package com.example.demo.handler;

import com.alibaba.fastjson.JSON;
import com.example.demo.dao.pojo.UserInfo;
import com.example.demo.service.TokenService;
import com.example.demo.util.UserThreadLocal;
import com.example.demo.vo.ErrorCode;
import com.example.demo.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    private TokenService tokenService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        // 再执行 controller 方法（handler）之前进行调用
        /**
         * 1. 需要判断请求的接口路径是否为 HandlerMethod（controller 方法）
         * 2. 判断 token 是否为空，表示未登录
         * 3. token 不为空，进行登录验证
         * 4. 如果认证成功，放行即可
         */
        if(!(handler instanceof HandlerMethod)){
            // handler 可能是访问的静态资源
            return true;
        }
        String token = request.getHeader("Authorization");

        log.info("======================== request start ========================");
        String requestURI = request.getRequestURI();
        log.info("request uri:{}", requestURI);
        log.info("request method:{}", request.getMethod());
        log.info("token:{}", token);
        log.info("======================== request   end ========================");

        if(!StringUtils.hasLength(token)){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        UserInfo userInfo = tokenService.checkToken(token);
        if(userInfo == null){
            Result result = Result.fail(ErrorCode.NO_LOGIN.getCode(), ErrorCode.NO_LOGIN.getMsg());
            response.setContentType("application/json;charset=utf8");
            response.getWriter().print(JSON.toJSONString(result));
            return false;
        }
        // 登录验证成功，放行
        // 希望在 controller 中直接获取用户的信息
        UserThreadLocal.put(userInfo);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        // 删除 ThreadLocal 中的用户信息（如果不删除，会有内存泄露风险）
        UserThreadLocal.remove();
    }
}
